import pandas as pd
import numpy as np
import lightgbm as lgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from datetime import timedelta

# 2. 数据预处理
# 假设你的数据已经加载到一个DataFrame中，列名为 date, sku, sales, season, launch_date, category。
# 假设df是你的数据
df = pd.read_csv('your_data.csv')

# 将日期转换为datetime格式
df['date_id'] = pd.to_datetime(df['date_id'])
df['launch_date'] = pd.to_datetime(df['launch_date'])

# 特征工程
df['days_since_launch'] = (df['date_id'] - df['launch_date']).dt.days
df['day_of_week'] = df['date_id'].dt.dayofweek
df['month'] = df['date_id'].dt.month

# 将类别特征转换为数值
df['season'] = df['season'].astype('category').cat.codes
df['category'] = df['category'].astype('category').cat.codes

# 选择特征和目标变量
features = ['sku', 'season', 'days_since_launch', 'day_of_week', 'month', 'category']
target = 'sales'

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(df[features], df[target], test_size=0.2, random_state=42)


# 3. 构建和训练LightGBM模型
# 创建LightGBM数据集
train_data = lgb.Dataset(X_train, label=y_train)
test_data = lgb.Dataset(X_test, label=y_test, reference=train_data)

# 设置模型参数
params = {
    'objective': 'regression',
    'metric': 'rmse',
    'boosting_type': 'gbdt',
    'num_leaves': 31,
    'learning_rate': 0.05,
    'feature_fraction': 0.9,
    'bagging_fraction': 0.8,
    'bagging_freq': 5,
    'verbose': 0
}

# 训练模型
model = lgb.train(params, train_data, num_boost_round=1000, valid_sets=[test_data], early_stopping_rounds=50)